<template>
  <div class="step-content">
    <el-form
      ref="uploadSetForm"
      :model="EduxcloudCourseLesson"
      :rules="uploadRules"
      label-width="120px"
      class="form-style"
    >
      <el-form-item v-if="sonSteps===1" label="标题名称" prop="title">
        <el-input v-model="EduxcloudCourseLesson.title" placeholder="请输入标题" style="width:80%;"/>
      </el-form-item>
      <el-form-item v-if="sonSteps===1" label="视频">
        <div>
          <el-tabs type="border-card" style="width:80%;" @tab-click="clickTab">
            <el-tab-pane label="上传资料">
              <el-col v-if="progressHidden" :span="13" style="margin-top: 6px;">
                <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"/>
              </el-col>
              <el-col :span="2" :offset="2" style="float: right;">
                <el-upload
                  v-if="!disable"
                  :before-upload="handleBefore"
                  :on-change="handleChange"
                  :http-request="uploadFileEnclosure"
                  :show-file-list="false"
                  action=""
                  class="upload-demo"
                >
                  <el-button slot="trigger" style="margin-left: -100px;">上传</el-button>
                </el-upload>
              </el-col>
              <div v-if="EduxcloudCourseLesson.mediaName">
                <span>{{ EduxcloudCourseLesson.mediaName }}</span>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form-item>
      <el-form-item v-if="sonSteps===1" label="视频时长">
        <el-input v-model="EduxcloudCourseLesson.videoMinute" style="width:30%;">
          <template slot="append">分</template>
        </el-input>
        <el-input v-model="EduxcloudCourseLesson.videoSecond" style="width:30%">
          <template slot="append">秒</template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="sonSteps===2" label="完成条件">
        <el-select v-model="EduxcloudCourseLesson.finishType">
          <el-option
            v-for="item in conditionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="sonSteps===2 && EduxcloudCourseLesson.finishType==='styleTime'"
        label="至少时长"
        prop="watchTime"
      >
        <el-input v-model="EduxcloudCourseLesson.watchTime" style="width:200px;">
          <template slot="append">分</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div class="step-btn">
      <el-button v-if="sonSteps===1" type="info" @click="goStep0">上一步</el-button>
      <el-button v-if="sonSteps===1" type="info" @click="goStep2">下一步</el-button>
      <el-button v-if="sonSteps===2" type="info" @click="goStep1">上一步</el-button>
      <el-button v-if="sonSteps===2" type="primary" @click="submitSave">保 存</el-button>
    </div>
  </div>
</template>
<script>
  import { addEnclosureFromVideo, getCreateUploadVideoUrl, getRefreshUploadVideoInfo, saveUsedRecord, upLoadFileToOss } from '@/api/subject/digitalAssets' // 数据接口
  import { getTenantId, getUserId, getUserName } from '@/utils/auth'
  import { addCourseLesson } from '@/api/subject/course_lesson'

  export default {
    props: {
      steps: {
        type: Number,
        default: 1
      },
      'home': Object
    },
    data() {
      return {
        sonSteps: this.steps,
        progressHidden: false,
        disable: false,
        percentage: 0,
        startloading: true,
        statusloading: false,
        sourceKeyWord: '',
        courseKeyWord: '',
        toLeadKeyWord: '',
        EduxcloudCourseLesson: {
          title: '',
          courseId: '',
          mediaName: '',
          videoId: '',
          chapterId: '',
          content: '',
          videoMinute: '',
          videoSecond: '',
          finishType: 'styleTime',
          watchTime: '1',
          mediaSource: 'upload'
        },
        uploadRules: {
          title: [{ required: true, message: '请输入标题', targger: 'blur' }],
          watchTime: [{ required: true, message: '请输入观看时长', targger: 'blur' }]
        },
        conditionOptions: [
          {
            value: 'styleOver',
            label: '学习到最后'
          },
          {
            value: 'styleTime',
            label: '学习时长'
          }
        ],
        sourceTableData: [
          {
            name: 'VID_20190320_095746.mp4',
            size: '20.38M',
            time: '2019/04/30 05:40'
          }
        ],
        attrs: {
          accept: 'image'
        }
      }
    },
    mounted() {
      // this.restaurants = this.loadAll()
      console.log('video.vue acceptEduxcloudCourseId:' + this.home.acceptEduxcloudCourseId)
      console.log('video.vue EduxcloudCourseLesson:' + this.EduxcloudCourseLesson)
      console.log('video.vue chapterId:' + this.home.chapterId)

      this.EduxcloudCourseLesson = this.home.EduxcloudCourseLesson
      if (!this.EduxcloudCourseLesson.courseId) {
        this.EduxcloudCourseLesson.courseId = this.home.acceptEduxcloudCourseId
      }
      if (!this.EduxcloudCourseLesson.chapterId) {
        this.EduxcloudCourseLesson.chapterId = this.home.chapterId
      }
    },
    methods: {
      // 上传之前
      handleBefore() {
      },
      // 上传封面
      handleChange(file) {
        this.file = file.raw
      },
      uploadFileEnclosure() {
        const type = this.file.name.substring(this.file.name.lastIndexOf('.') + 1)
        const name = this.file.name.substring(0, this.file.name.lastIndexOf('.'))
        const videoArr = ['AVI', 'MKV', 'MOV', 'MP4', 'TS', 'RMVB', 'WMV', 'XVID', 'X264', 'X265', 'MPG']
        if (videoArr.indexOf(type.toLocaleUpperCase()) !== -1) {
          const userData = '{"Vod":{}} '
          const uploader = this.createUploader()
          uploader.addFile(this.file, null, null, null, userData)
          uploader.startUpload()
        } else {
          setTimeout(() => {
            const fileForm = new FormData()
            fileForm.append('name', name)
            fileForm.append('type', type)
            fileForm.append('file', this.file)
            fileForm.append('assetsUnitId', this.EduxcloudCourse.id)
            fileForm.append('creator', getUserName())
            fileForm.append('tenantId', getTenantId())
            upLoadFileToOss(fileForm).then(res => {
              console.log('name: ' + name)
              this.EduxcloudCourseLesson.mediaName = res.data
              this.$notify({
                title: '成功',
                message: '文件上传成功',
                type: 'success',
                duration: 2000
              })
            })
          }, 100)
        }
      },
      createUploader() {
        /* eslint-disable */
        const _this = this
        const uploader = new AliyunUpload.Vod({
          timeout: 60000,
          partSize: 1048576,
          parallel: 5,
          retryCount: 3,
          retryDuration: 2,
          region: '',
          userId: '1560516061941369',

          // 添加文件成功
          addFileSuccess: function(uploadInfo) {
            // 显示上传进度
            _this.progressHidden = true
            console.log('addFileSuccess: ' + uploadInfo.file.name + ' uploadInfo.videoId: ' + uploadInfo.videoId)
          },
          // 开始上传
          onUploadstarted: function(uploadInfo) {
            console.log('uploadInfo.videoId:' + uploadInfo.videoId)
            if (uploadInfo.videoId) {
              getRefreshUploadVideoInfo(uploadInfo.videoId).then(res => {
                const uploadAuth = res.UploadAuth
                const uploadAddress = res.UploadAddress
                const videoId = res.VideoId
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
              })
              console.log('videoId: ' + uploadInfo.videoId)
            } else {
              const title = uploadInfo.file.name.substring(0, uploadInfo.file.name.lastIndexOf('.'))
              const fileForm = new FormData()
              fileForm.append('title', title)
              fileForm.append('fileName', uploadInfo.file.name)
              getCreateUploadVideoUrl(fileForm).then(res => {

                const uploadAuth = res.data.result.UploadAuth
                const uploadAddress = res.data.result.UploadAddress
                const videoId = res.data.result.VideoId
                console.log('uploadAuth' + uploadAuth + ',uploadAddress：' + uploadAddress + ',videoId：' + videoId)
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
              })
              console.log('onUploadStarted:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
            }
          },
          // 文件上传成功
          onUploadSucceed: function(uploadInfo) {
            console.log('onUploadSucceed: ' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
            const endpoint = uploadInfo.endpoint.split('//')[1]
            const url = 'https://' + uploadInfo.bucket + '.' + endpoint + '/' + uploadInfo.object // URL
            const id = uploadInfo.videoId.trim()
            const name = uploadInfo.file.name.trim()
            const assetsId = _this.EduxcloudCourseLesson.courseId
            _this.EduxcloudCourseLesson.videoId = id
            _this.EduxcloudCourseLesson.mediaName = name
            console.log('videoId: ' + id + ', name:' + name + ',size:' + uploadInfo.size)
            if (uploadInfo.duration) {
              console.log('duration: ' + uploadInfo.duration)
              let duration = uploadInfo.duration
              let m = Math.floor((duration / 60 % 60)) < 10 ? '0' + Math.floor((duration / 60 % 60)) : Math.floor((duration / 60 % 60))
              let s = Math.floor((duration % 60)) < 10 ? '0' + Math.floor((duration % 60)) : Math.floor((duration % 60))
              _this.EduxcloudCourseLesson.videoMinute = m
              _this.EduxcloudCourseLesson.videoSecond = s
            }
            const fileForm = new FormData()
            _this.progressHidden = false
            _this.percentage = 0
            fileForm.append('url', url)
            fileForm.append('fileId', id)
            fileForm.append('fileName', name)
            fileForm.append('assetsUnitId', assetsId)
            fileForm.append('creator', getUserName())
            fileForm.append('tenantId', getTenantId())
            addEnclosureFromVideo(fileForm).then(() => {
              // _this.getEnclosure(assetsId);
              console.log('fileName: ' + name)
              _this.$notify({
                title: '成功',
                message: '文件上传成功',
                type: 'success',
                duration: 2000
              })
            })
          },
          // 文件上传失败
          onUploadFailed: function(uploadInfo, code, message) {
            console.log('onUploadFailed: file:' + uploadInfo.file.name + ',code:' + code + ', message:' + message)
            _this.$message.error('文件上传失败!')
          },
          // 取消文件上传
          onUploadCanceled: function(uploadInfo, code, message) {
            console.log('Canceled file: ' + uploadInfo.file.name + ', code: ' + code + ', message:' + message)
            _this.$message.warning('文件上传已暂停!')
          },
          // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
          onUploadProgress: function(uploadInfo, totalSize, progress) {
            // console.log('onUploadProgress:file:' + uploadInfo.file.name + ', fileSize:' + totalSize + ', percent:' + Math.ceil(progress * 100) + '%')
            const progressPercent = Math.ceil(progress * 100)
            _this.percentage = progressPercent
            if (progressPercent === 100) {
              const recordForm = new FormData()
              recordForm.append('size', totalSize)
              recordForm.append('userId', getUserId())
              saveUsedRecord(recordForm)
              // console.log('totalSize: ' + totalSize)
            }
          },
          // 上传凭证超时
          onUploadTokenExpired: function(uploadInfo) {
            _this.$message.error('文件上传超时!')
            getRefreshUploadVideoInfo(uploadInfo.videoId).then(res => {
              const uploadAuth = res.data.result.UploadAuth
              uploader.resumeUploadWithAuth(uploadAuth)
              console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
            })
          },
          // 全部文件上传结束
          onUploadEnd: function() {
            _this.$notify({ title: '成功', message: '文件上传完毕!', type: 'success', duration: 2000 })
            // console.log('onUploadEnd: uploaded all the files')
          }
        })
        return uploader
      },
      goStep0() {
        this.$emit('nowStep0')
      },
      goStep1() {
        this.sonSteps = 1
        this.$emit('nowStep1')
      },
      goStep2() {
        this.$refs.uploadSetForm.validate((valid) => {
          if (valid) {
            this.sonSteps = 2
            this.$emit('nowStep2')
          } else {
            return false
          }
        })
      },
      submitSave() {
        this.$refs['uploadSetForm'].validate((valid) => {
          if (valid) {
            this.EduxcloudCourseLesson.tenantId = getTenantId()
            this.EduxcloudCourseLesson.userId = getUserId()
            addCourseLesson(this.EduxcloudCourseLesson).then(response => {
              if (response.code === 200) {
                this.EduxcloudCourseLesson = {}
                this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
                this.$emit('saveInfo')
              }
            })
          }
        })
      },
      editFile() {
        this.uploadSetForm.file = ''
      },
      loadAll() {
        return [
          { 'value': '高三数学', 'address': '上海市长宁区天山西路' },
          { 'value': '语文模拟', 'address': '上海市长宁区金钟路968号15楼15-105室' }
        ]
      },
      querySearchAsync(queryString, cb) {
        var restaurants = this.restaurants
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants

        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 1000 * Math.random())
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      handleSelect(item) {
        console.log(item)
        this.uploadSetForm.file = item.value
      },
      clickTab(tab) {
        if (tab.label === '从资料库中选择') {
          this.startloading = false
        }
      },
      tableClick(row) {
        this.uploadSetForm.file = row.name
      },
      loading() {
        if (this.startloading === false) {
          this.startloading = true
          this.statusloading = true
          this.sourceTableData.push(
            {
              name: 'VID_20190320_095746.mp4',
              size: '18.20M',
              time: '2019-06-03 15:30'
            }
          )
          setTimeout(() => {
            this.statusloading = false
          }, 1000)
          this.startloading = false
        }
      },
      onFileAdded(rootFile) {
        // console.log(rootFile)
      },
      onFileProgress(rootFile, file, response) {
      },
      onFileError(rootFile, file, response, chunk) {
        // console.log(rootFile, file, response, chunk)
      },
      onFileSuccess: function(rootFile, file, response, chunk) {
        //这里可以根据response（接口）返回的数据处理自己的实际问题（如：从response拿到后台返回的想要的数据进行组装并显示）
        //注，这里从文件夹每上传成功一个文件会调用一次这个方法
      }
    }
  }
</script>
<style lang="scss" scoped>
  .step-content {
    min-height: 50px;

    .form-style {
      min-height: 80px;
      border-bottom: 1px solid #eee;
      margin-top: 20px;
      padding: 0 20px;
    }

    .step-btn {
      margin-top: 20px;
      text-align: right;
    }

    .info-hint {
      color: #a1a1a1;
    }

    .loading-box {
      margin-top: 10px;
      max-height: 200px;
      overflow: auto;
    }

    div {
      /deep/ .el-tabs--border-card {
        box-shadow: none;

        .el-tabs {
          border-radius: 2px;
        }

        .el-tabs__header {
          margin: 0;
        }
      }
    }

    .uploader-example {
      width: 100%;
      padding: 15px;
      margin: 0 auto 0;
      font-size: 12px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);

      .uploader-drop {
        text-align: center;
      }

      .uploader-btn {
        margin-right: 4px;
      }

      .uploader-list {
        max-height: 440px;
        overflow: auto;
        overflow-x: hidden;
      }
    }
  }
</style>
